package com.dup.fastgpt.config;

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

@Configuration
public class RestTemplateConfig {
	@Bean
	public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
		// 创建信任所有证书的策略（仅限开发环境）
		TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

		// 构建SSL上下文
		SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
				.loadTrustMaterial(null, acceptingTrustStrategy)
				.build();

		// 创建SSL Socket Factory
		SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(
				sslContext,
				NoopHostnameVerifier.INSTANCE);

		// 创建HttpClient
		CloseableHttpClient httpClient = HttpClients.custom()
				.setSSLSocketFactory(csf)
				.build();

		// 创建RequestFactory
		HttpComponentsClientHttpRequestFactory requestFactory =
				new HttpComponentsClientHttpRequestFactory(httpClient);
		requestFactory.setConnectTimeout(5000);  // 5秒连接超时
		requestFactory.setReadTimeout(30000);    // 30秒读取超时

		return new RestTemplate(requestFactory);
	}
}
